#!/bin/sh

PROG_NAME="yocto-setup.sh"

# 忽略以 twr 开头的的文件
MACHINE_EXCLUSION="^twr"
# Which machine types are ARM based and need the linaro toolchain?
# This should be done properly by checking the conf files, really
ARM_MACHINE="^ls|^s32|^lx|^imx"

DEFAULT_DISTRO="fsl-auto"
COMPANY="ALPHA"

# Supported yocto version
YOCTO_VERSION="kirkstone"

# Error codes
EINVAL=128

if [ -z "$ZSH_NAME" ] && echo "$0" | grep -q "$PROG_NAME"; then
    echo "ERROR: This script needs to be sourced."
    SCRIPT_PATH=`readlink -f $0`
    if [ "`readlink $SHELL`" = "dash" ];then
        echo "Try run command \"set -- -h; . $SCRIPT_PATH\" to get help."
    else
        echo "Try run command \". $SCRIPT_PATH -h\" to get help."
    fi
    unset SCRIPT_PATH PROG_NAME
    exit
else
    if [ -n "$BASH_SOURCE" ]; then
        ROOT_DIR="`readlink -f $BASH_SOURCE | xargs dirname`"
    elif [ -n "$ZSH_NAME" ]; then
        ROOT_DIR="`readlink -f $0 | xargs dirname`"
    else
        ROOT_DIR="`readlink -f $PWD | xargs dirname`"
    fi
    if ! [ -e "$ROOT_DIR/$PROG_NAME" ];then
        echo "Go to where $PROG_NAME locates, then run: . $PROG_NAME <args>"
        unset ROOT_DIR PROG_NAME
        return
    fi
fi

SOURCES_DIR="sources"
ALB_ROOT_DIR=${ROOT_DIR}/${SOURCES_DIR}/meta-alb

OE_ROOT_DIR=${ROOT_DIR}/${SOURCES_DIR}/poky
if [ -e ${ROOTDIR}/${SOURCES_DIR}/oe-core ]; then
    OE_ROOT_DIR=${ROOT_DIR}/${SOURCES_DIR}/oe-core
fi
FSL_ROOT_DIR=${ROOT_DIR}/${SOURCES_DIR}/meta-freescale
PROJECT_DIR=${ROOT_DIR}/build_${MACHINE}

# Check if current user is root
if [ "$(whoami)" = "root" ]; then
    echo "ERROR: Do not use the BSP as root. Exiting..."
    unset ROOT_DIR PROG_NAME
    return
fi

prompt_message () {
local i=''
echo "Welcome to ${COMPANY} Auto Linux BSP (Reference Distro)

The Yocto Project has extensive documentation about OE including a
reference manual which can be found at:
    http://yoctoproject.org/documentation

For more information about OpenEmbedded see their website:
    http://www.openembedded.org/

You can now run 'bitbake <target>'
"
    echo "Targets specific to ${COMPANY}:"
    for layer in $(echo $LAYER_LIST | xargs); do
        fsl_recipes=$(find ${ROOT_DIR}/${SOURCES_DIR}/$layer -path "*recipes-*/images/fsl*.bb" -or -path "images/fsl*.bb" 2> /dev/null)
        if [ -n "$fsl_recipes" ]
        then
            for i in $(echo $fsl_recipes | xargs);do
                i=$(basename $i);
                i=$(echo $i | sed -e 's,^\(.*\)\.bb,\1,' 2> /dev/null)
                echo "    $i";
            done
        fi
    done

    echo "To return to this build environment later please run:"
    echo "    . $PROJECT_DIR/SOURCE_THIS"
}

clean_up()
{
   unset PROG_NAME ROOT_DIR OE_ROOT_DIR FSL_ROOT_DIR PROJECT_DIR \
         EULA EULA_FILE LAYER_LIST MACHINE FSL_DISTRO \
         OLD_OPTIND CPUS JOBS THREADS DOWNLOADS CACHES DISTRO \
         setup_flag setup_h setup_j setup_t setup_l setup_builddir \
         setup_download setup_sstate setup_error layer append_layer \
         extra_layers distro_override MACHINELAYER MACHINEEXCLUSION \
         ARMMACHINE

   unset -f usage prompt_message
}

usage() {
    echo "Usage: . $PROG_NAME -m <machine>"
    ls $FSL_ROOT_DIR/conf/machine/*.conf > /dev/null 2>&1

    if [ $? -eq 0 ]; then
        echo -n -e "\n    Supported machines: "
        for layer in $(eval echo $USAGE_LIST); do
            if [ -d ${ROOT_DIR}/${SOURCES_DIR}/${layer}/conf/machine ]; then
                echo -n -e "`ls ${ROOT_DIR}/${SOURCES_DIR}/${layer}/conf/machine | grep "\.conf" \
                   | egrep -v "^${MACHINEEXCLUSION}" | sed s/\.conf//g | xargs echo` "
            fi
        done
        echo ""
    else
        echo "    ERROR: no available machine conf file is found. "
    fi

    echo "    Optional parameters:
    * [-m machine]: the target machine to be built.
    * [-b path]:    non-default path of project build folder.
    * [-e layers]:  extra layer names
    * [-D distro]:  override the default distro selection ($DEFAULT_DISTRO)
    * [-j jobs]:    number of jobs for make to spawn during the compilation stage.
    * [-t tasks]:   number of BitBake tasks that can be issued in parallel.
    * [-d path]:    non-default path of DL_DIR (downloaded source)
    * [-c path]:    non-default path of SSTATE_DIR (shared state Cache)
    * [-l]:         lite mode. To help conserve disk space, deletes the building
                    directory once the package is built.
    * [-h]:         help
"
    if [ "`readlink $SHELL`" = "dash" ];then
        echo "
    You are using dash which does not pass args when being sourced.
    To workaround this limitation, use \"set -- args\" prior to
    sourcing this script. For exmaple:
        \$ set -- -m s32g274ardb2 -j 3 -t 2
        \$ . $ROOT_DIR/$PROG_NAME
"
    fi
}

add_layers_for_machines()
{
    # add the layer specified in PARAM_LAYER_LIST only for the machines
    # contained in PARAM_MACHINE_LIST

    PARAM_LAYER_LIST=$1
    PARAM_MACHINE_LIST=$2

    echo ${MACHINE} | egrep -q "${PARAM_MACHINE_LIST}"
    if [ $? -eq 0 ]; then
        for layer in $(eval echo ${PARAM_LAYER_LIST}); do
            if [ -e "${ROOT_DIR}/${SOURCES_DIR}/${layer}" ]; then
                LAYER_LIST="$LAYER_LIST \
                    $layer \
                "
            fi
        done
    fi
}

is_not_ubuntu_machine()
{
    echo ${MACHINE} | egrep -q "${UBUNTU_MACHINE}"
    return $?
}

# parse the parameters
OLD_OPTIND=$OPTIND
while getopts "m:j:t:b:d:e:D:c:lh" setup_flag
do
    case $setup_flag in
        m) MACHINE="$OPTARG";
           ;;
        j) setup_j="$OPTARG";
           ;;
        t) setup_t="$OPTARG";
           ;;
        b) setup_builddir="$OPTARG";
           ;;
        d) setup_download="$OPTARG";
           ;;
        e) extra_layers="$OPTARG";
           ;;
        D) distro_override="$OPTARG";
           ;;
        c) setup_sstate="$OPTARG";
           ;;
        l) setup_l='true';
           ;;
        h) setup_h='true';
           ;;
        ?) setup_error='true';
           ;;
    esac
done
OPTIND=$OLD_OPTIND

IMX_LAYER_LIST=" \
    meta-openembedded/meta-oe \
    meta-openembedded/meta-multimedia \
    meta-openembedded/meta-python \
    meta-openembedded/meta-gnom \
    meta-openembedded/meta-networking \
    meta-openembedded/meta-filesystems \
    meta-freescale \
    meta-freescale-3rdparty \
    meta-freescale-distro \
    meta-imx/meta-bsp \
    meta-imx/meta-sdk \
    meta-imx/meta-ml \
    meta-imx/meta-v2x \
    meta-nxp-demo-experience \
    meta-browser/meta-chromium \
    meta-clang \
    meta-qt6 \
    meta-virtualization \
    $extra_layers \
"

S32_LAYER_LIST=" \
    meta-openembedded/meta-oe \
    meta-openembedded/meta-multimedia \
    meta-openembedded/meta-python \
    meta-openembedded/meta-python2 \
    meta-openembedded/meta-networking \
    meta-openembedded/meta-gnome \
    meta-openembedded/meta-filesystems \
    meta-openembedded/meta-webserver \
    meta-openembedded/meta-perl \
    meta-openembedded/meta-xfce \
    meta-virtualization \
    meta-security \
    meta-freescale \
    meta-alb \
    meta-alb-dev \
    meta-aa-integration \
    meta-vnp \
    meta-gvip \
    meta-qoriq \
    $extra_layers \
"

echo ${MACHINE} | egrep -q "${ARMMACHINE}"
if [[ $MACHINE == s32* ]]; then
    USAGE_LIST="$S32_LAYER_LIST"
    add_layers_for_machines "${S32_LAYER_LIST}" "${BBLSMACHINE}"
else
    USAGE_LIST="$IMX_LAYER_LIST"

fi